import { defineStore } from "pinia";
import { store } from "../index";

interface AdminStore {
  menus: MenusType[];
}

// interface Recordable  {
//   [key: number]: MenusType
// }

export const useAdminStore = defineStore("admin", {
  state(): AdminStore {
    return {
      menus: [],
    };
  },
  actions: {
    updateMenus(menus: MenusType[]) {
      this.menus = menus;
    },
  },
  getters: {
    genNewMenus(state) {
      console.log(state);
      // extends约束  in:映射（循环）for(let key in obj)
      // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
      const newMenus: Recordable<MenusType> = {};
      // {7: {children: [{子菜单}, {子菜单}]}}
      state.menus.forEach((menu) => {
        if (menu.parentId === 0) {
          newMenus[menu.id] = {
            ...menu,
            children: newMenus[menu.parentId]?.children ?? [],
          };
        } else {
          // 子菜单所对应的父的id
          newMenus[menu.parentId] ??= {} as MenusType;
          newMenus[menu.parentId].children ??= [];
          newMenus[menu.parentId].children.push(menu);
        }
      });

      return newMenus;
    },
  },
});

// 在setup外使用
export const useAdminStoreWithOut = () => useAdminStore(store);

/* // 父： 广； 子： 具体(协变)
let a: { name: string };
let b: { name: string; age: number };
a = b;
b = a;

// 逆变 函数参数 父可以赋值给子
let fn = (p: typeof a) => {
  console.log(p.name);
};
let fn1 = (p: typeof b) => {
  console.log(p.age);
};
fn = fn1;
fn1 = fn; */
